package com.aitaoxue.palx.ui.register;

import java.util.regex.Pattern;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.InjectView;

import com.aitaoxue.palx.AppManager;
import com.aitaoxue.palx.R;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.BaseActivity;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class RegisterActivity extends BaseActivity {
	@InjectView(R.id.phone)
	EditText phone;
	@InjectView(R.id.alert_line)
	RelativeLayout layout;
	@InjectView(R.id.btn_push)
	Button push;
	@InjectView(R.id.alert_content)
	TextView alert;

	Pattern pattern = Pattern.compile("^\\d{11}$");

	@Override
	protected boolean hasBackButton() {
		return true;
	}

	@Override
	protected int getActionBarTitle() {
		return R.string.register;
	}

	@Override
	protected int getLayoutId() {
		return R.layout.activity_register;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_push:
			if (TextUtils.isEmpty(phone.getText())) {
				showToast("请输入手机号码", 0, 0);
			} else if (!pattern.matcher(phone.getText().toString()).matches()) {
				showToast("请输入正确的手机号码", 0, 0);
			} else {
				String number = phone.getText().toString();

				showWaitDialog();
				AitaoXueApi.sendchecknum(number, mHandler);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void initView() {
		push.setOnClickListener(this);
		
		AppManager.getAppManager().addActivity(this);
	}

	@Override
	public void initData() {

	}

	private AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			hideWaitDialog();
			String res = new String(arg2);

			try {
				JSONObject json = new JSONObject(res);

				String code = json.getString("code");

				switch (code) {
				case "0000": // 成功
					Intent intent = new Intent(RegisterActivity.this,
							RegisterActivity2.class);
					intent.putExtra("phone", phone.getText().toString());
					startActivity(intent);
					//finish();
					break;
				case "0302": // 手机号输入不正确
					showError("手机号输入不正确");
					break;
				case "0306":
					showError("此手机号已注册");
					break;
				case "0307":
					showError("此手机号已在家长端注册");
					break;
				case "0310":
					showError("点击次数太频繁");
					break;
				default:
					break;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
		}
	};

	private void showError(String error) {
		if (layout.getVisibility() == View.GONE) {
			layout.setVisibility(View.VISIBLE);
		}
		alert.setText(error);
	}

}
